#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:    御风
# @Mail:      zhong.yufeng@foxmail.com
# @Time:      2022/4/8 22:39


import argparse
import config
from flask import Flask, request
from flask_caching import Cache
from views.goods import route as goods
from views.admin import route as admin
from views.admin.check import checkLogin
from utils.session.session import Session

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
app.config["JSONIFY_MIMETYPE"] = "application/json;charset=utf-8"
app.cache = Cache(app=app, config=config.CACHE_CONFIG)

app.register_blueprint(goods, url_prefix="/goods")
app.register_blueprint(admin, url_prefix="/admin")


@app.before_request
def beforeRequest():
    url = request.path
    checkUrl = {
        "/admin/info":    ["GET"],
        "/admin/change":  ["GET"],
        "/goods/product": ["POST", "DELETE", "PUT"],
    }
    if url in checkUrl and request.method in checkUrl[url]:
        return checkLogin()


@app.after_request
def afterRequest(response):
    Session.save(response)
    return response


def run():
    parser = argparse.ArgumentParser()
    parser.add_argument("-host", nargs="?", dest="host", type=str, help="服务器地址", default=config.SERVER_HOST)
    parser.add_argument("-port", nargs="?", dest="port", type=int, help="服务器端口", default=config.SERVER_PORT)
    parser.add_argument("-debug", nargs="?", dest="debug", type=bool, help="调试模式", default=False)
    args = parser.parse_args()
    app.run(host=args.host, port=args.port, threaded=True, debug=args.debug)


if __name__ == "__main__":
    run()
